<template>
  <el-dialog width="600px" :visible.sync="isShow" :show-close="false" class="register">
    <div class="title" slot="title">用户注册</div>
    <el-form class="form" ref="form" :model="form" :rules="rules" label-width="80px">
      <!-- 头像上传 -->
      <el-form-item label="头像" prop="avatar">
        <el-upload
          class="avatar-uploader"
          :action="baseUrl + '/uploads'"
          name="image"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
        >
          <img v-if="form.avatar" :src="baseUrl+'/'+form.avatar" class="avatar" />
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>

      <el-form-item label="昵称" prop="username">
        <el-input v-model="form.username" placeholder="请输入昵称"></el-input>
      </el-form-item>

      <el-form-item label="邮箱" prop="email">
        <el-input placeholder="请输入邮箱" v-model="form.email"></el-input>
      </el-form-item>

      <el-form-item label="手机" prop="phone">
        <el-input v-model="form.phone" placeholder="请输入手机号"></el-input>
      </el-form-item>

      <el-form-item label="密码" prop="password">
        <el-input v-model="form.password" placeholder="请输入密码"></el-input>
      </el-form-item>

      <el-form-item label="图形码" prop="code">
        <el-row>
          <el-col :span="15">
            <el-input v-model="form.code" placeholder="请输入图形验证码"></el-input>
          </el-col>
          <el-col :span="8" :offset="1">
            <img :src="baseUrl+codeUrl" alt class="rcodeimg" @click="rcodeimg" />
          </el-col>
        </el-row>
      </el-form-item>

      <el-form-item label="验证码" prop="rcode">
        <el-row>
          <el-col :span="15">
            <el-input v-model="form.rcode" placeholder="请输入验证码"></el-input>
          </el-col>
          <el-col :span="8" :offset="1">
            <el-button class @click="rcodeClick" :disabled="totalTime!=5">
              获取用户验证码
              <span v-if="totalTime!=5">({{totalTime}})</span>
              <!-- <span v-else="totalTime != 5"></span> -->
            </el-button>
          </el-col>
        </el-row>
      </el-form-item>
    </el-form>

    <div class="footer" slot="footer">
      <el-button @click="isShow = false">取消</el-button>
      <el-button type="primary" @click="submit">确定</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { getPhoneCode, toRegister } from "@/api/register.js";
export default {
  watch: {
    isShow(newVal) {
      if (newVal == false) {
        this.$refs.form.resetFields();
      }
    },
  },
  data() {
    return {
      form: {
        avatar: "",
        username: "",
        email: "",
        phone: "",
        password: "",
        code: "",
        rcode: "",
      },
      rules: {
        avatar: [{ required: true, message: "请上传头像", trigger: "change" }],
        username: [
          { required: true, message: "请输入昵称", trigger: "change" },
        ],
        email: [
          { required: true, message: "请输入邮箱号码", trigger: "change" },
          {
            validator: (rule, value, callback) => {
              let reg = /\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/;
              if (reg.test(value)) {
                callback();
              } else {
                callback(new Error("请输入正确的邮箱号码"));
              }
            },
            trigger: "change",
          },
        ],
        phone: [
          { required: true, message: "请输入手机号码", trigger: "change" },
          {
            validator: (rule, value, callback) => {
              let reg = /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/;
              if (reg.test(value)) {
                callback();
              } else {
                callback(new Error("请输入正确的手机号码"));
              }
            },
            trigger: "change",
          },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "change" },
          {
            min: 6,
            max: 8,
            message: "请输入6-8位密码",
            trigger: "change",
          },
        ],
        code: [{ message: "请输入图形验证码", trigger: "change" }],
        rcode: [{ message: "请输入验证码", trigger: "change" }],
      },
      totalTime: 5,
      isShow: false,
      imageUrl: "",
      codeUrl: "/captcha?type=sendsms",
      baseUrl: process.env.VUE_APP_URL,
    };
  },
  methods: {
    handleAvatarSuccess(res) {
      // this.imageUrl = res.data.file_path;
      this.form.avatar = res.data.file_path;
      this.$refs.form.validateField(["avatar"]);
      //   this.imageUrl = URL.createObjectURL(file.raw);
    },
    beforeAvatarUpload(file) {
      const isJPG =
        file.type === "image/jpeg" ||
        file.type === "image/png" ||
        file.type === "image/gif";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
    submit() {
      this.$refs.form.validate((result) => {
        if (result) {
          toRegister(this.form).then((res) => {
            console.log(res);
            // if (res.data.code == 200) {
              this.$message.success("注册成功");
              this.isShow = false;
            // }
          });
        } else {
          this.$message.error("验证失败");
        }
      });
    },

    // 修改图像验证码 
    rcodeimg() {
      this.codeUrl = "/captcha?type=sendsms&tr"+Math.random()*67;
    },

    //获取手机验证码
    rcodeClick() {
      let num = 0;
      this.$refs.form.validateField(["phone", "code"], (error) => {
        console.log(error);
        if (error == "") {
          num++;
        }
      });
      if (num == 2) {
        //获取验证码倒计时
        this.totalTime--;
        let time = setInterval(() => {
          this.totalTime--;
          if (this.totalTime == 0) {
            this.totalTime = 5;
            clearInterval(time);
          }
        }, 1000);

        getPhoneCode({
          code: this.form.code,
          phone: this.form.phone,
        }).then((res) => {
          // console.log(res);

          if (res.data.code == 200) {
            
            this.$message.success(res.data.data.captcha + "");
          } else {
            this.$message.error(res.data.message);
            
          }
        });
      } else {
        this.$message.error("验证失败");
      }
    },
  },
};
</script>

<style lang='less'>
.register {
  .title {
    height: 53px;
    background: linear-gradient(to right, #01c4fa, #1295fa);
    text-align: center;
    line-height: 53px;
  }
  .el-dialog__header {
    padding: 0;
  }
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409eff;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
  .footer {
    text-align: center;
  }
  .rcodeimg {
    height: 40px;
  }
}
</style>